package com.ishanggang.service;

import com.ishanggang.entity.IsgActivityDictShopInfo;
import com.ishanggang.entity.IsgDictShopInfo;
import com.ishanggang.entity.IsgICDictShopInfo;
import com.ishanggang.mapper.IsgActivityDictStoreInfoMapper;
import com.ishanggang.mapper.IsgDictStoreInfoMapper;
import com.ishanggang.mapper.IsgDictStoreKaMapper;
import com.ishanggang.mapper.IsgICDictStoreInfoMapper;
import com.ishanggang.util.GaoDeLatAndLngUtil;
import com.ishanggang.util.GeoHashUtil;
import com.mysql.jdbc.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Map;

@Slf4j
@Service
public class QuickBiService {

  private static final Logger logger = LoggerFactory.getLogger(QuickBiService.class);
  @Resource
  private IsgDictStoreInfoMapper isgDictStoreInfoMapper;
  @Resource
  private IsgICDictStoreInfoMapper isgICDictStoreInfoMapper;
  @Resource
  private IsgActivityDictStoreInfoMapper isgActivityDictStoreInfoMapper;
  @Resource
  private IsgDictStoreKaMapper isgDictStoreKaMapper;
  @Resource
  private GeoHashUtil geoHashUtil;
  public static final String QUICK_BI_STORE_GEOHASH_KEY = "QUICK_BI_STORE_GEOHASH_KEY";
  public static final Integer DISTANCE = 2;
  private static final Double MAX_JUDGE_DISTANCE = 1.0;
  public static final Integer totalCount = 300;
  // 距离每增加 100 M,匹配度得分扣 N 目前设置为5
  private static final Integer DISTANCE_PER_HUNDRED_M_SCORE = 5;
  // ka 名称每匹配一个字,加 5 分
  private static final Integer KA_NAME_PER_WORD_MATCH_SCORE = 5;
  // 门店 名称每匹配一个字,加 3 分
  private static final Integer STORE_NAME_PER_WORD_MATCH_SCORE = 3;
  // 门店 地址每匹配一个字,加 3 分
  private static final Integer STORE_ADDRESS_PER_WORD_MATCH_SCORE = 3;



  public void initRedisJddjStoreInfo() {
    Long maxId = this.isgDictStoreInfoMapper.selectMaxId();
    Long i = 1L;
    while (true) {
      this.initRedisJddjStoreItem(i);
      if (i > maxId) {
        break;
      }
      i++;
    }
  }


  public void initRedisJddjStoreItem(Long id) {
    IsgDictShopInfo isgDictShopInfo = this.isgDictStoreInfoMapper.selectById(id);
    if (isgDictShopInfo != null) {
      try {
        this.geoHashUtil.redisGeoAdd(QUICK_BI_STORE_GEOHASH_KEY,
            Double.parseDouble(isgDictShopInfo.getLongitude()),
            Double.parseDouble(isgDictShopInfo.getLatitude()), String.valueOf(isgDictShopInfo.getId()));
        logger.info("=================={}", isgDictShopInfo.getId());
      } catch (Exception e) {
        logger.error("转化异常", e);
      }
    }
  }


  /**
   * 校验是否重复
   */
  public void checkSameShop() {
    Long maxId = this.isgICDictStoreInfoMapper.selectMaxId();
    Long i = 1L;
    while (true) {
      this.checkStoreItemSame(i);
      if (i > maxId) {
        break;
      }
      i++;
    }
  }

  /**
   * 校验单个门店是否重复
   * @param id
   */
  private void checkStoreItemSame(Long id) {
    IsgDictShopInfo isgDictShopInfo = this.isgDictStoreInfoMapper.selectById(id);
    if (isgDictShopInfo == null) {
      return;
    }
    String shopKa = isgDictStoreKaMapper.selectKaByBusCode(isgDictShopInfo.getBusCode());
    if (StringUtils.isNullOrEmpty(shopKa)) {
      logger.info("bussCode{}的商家为空{}", isgDictShopInfo.getBusCode(), shopKa);
    }
    try {
      GeoResults<RedisGeoCommands.GeoLocation<String>> geoResults = this.geoHashUtil.redisNearByXY(
              QUICK_BI_STORE_GEOHASH_KEY, Double.parseDouble(isgDictShopInfo.getLongitude()),
              Double.parseDouble(isgDictShopInfo.getLatitude()), DISTANCE, totalCount);
      for (GeoResult<RedisGeoCommands.GeoLocation<String>> item : geoResults.getContent()) {
        Long shopId = Long.parseLong(item.getContent().getName());
        if (isgDictShopInfo.getId().equals(shopId) || isgDictShopInfo.getId() <= shopId) {
          continue;
        }
        IsgDictShopInfo isgSameDictShop = this.isgDictStoreInfoMapper.selectById(shopId);
        if (!ObjectUtils.isEmpty(isgSameDictShop)) {
          String sameShopKa = isgDictStoreKaMapper.selectKaByBusCode(isgSameDictShop.getBusCode());
          // 距离相近且商家相同--认为是同一家门店
          if (sameShopKa.equals(shopKa)) {
            isgDictStoreInfoMapper.updateSameShopFlag(isgDictShopInfo.getId(), shopId
                    , shopKa, item.getDistance().getValue());
            break;
          }
        }
      }
    } catch (Exception e) {
      logger.error("转化异常", e);
    }
  }

  /**
   * 联合立华门店-匹配完美门店
   */
  public void checkIcShop() {
    Long maxId = this.isgICDictStoreInfoMapper.selectMaxId();
    Long i = 19L;
    while (true) {
      this.checkIcItemShop(i);
      if (i > maxId) {
        break;
      }
      i++;
    }
  }

  /**
   * 校验单个门店是否重复
   * @param id
   */
  private void checkIcItemShop(Long id) {
    IsgICDictShopInfo icDirectShopInfo = isgICDictStoreInfoMapper.selectById(id);
    if (ObjectUtils.isEmpty(icDirectShopInfo)||StringUtils.isNullOrEmpty(icDirectShopInfo.getKaName())) {
      logger.info("bussCode{}的商家为空", icDirectShopInfo);
      return;
    }
    String shopKa = icDirectShopInfo.getKaName();
    logger.info("============={}", icDirectShopInfo);
    try {
      if (icDirectShopInfo.getLatitude() == null || icDirectShopInfo.getLongitude() == null) {
        Map queChaoBaiduLatAndLngMap = null;
        queChaoBaiduLatAndLngMap = GaoDeLatAndLngUtil.addressToLngAndLag(
                (String) icDirectShopInfo.getShopAddress());
        String brandShopLng =(String) queChaoBaiduLatAndLngMap.get("lng");
        String brandShopLat = (String) queChaoBaiduLatAndLngMap.get("lat");
        icDirectShopInfo.setLatitude(brandShopLat);
        icDirectShopInfo.setLongitude(brandShopLng);
      }
      GeoResults<RedisGeoCommands.GeoLocation<String>> geoResults = this.geoHashUtil.redisNearByXY(
              QUICK_BI_STORE_GEOHASH_KEY, Double.parseDouble(icDirectShopInfo.getLongitude()),
              Double.parseDouble(icDirectShopInfo.getLatitude()), DISTANCE, totalCount);
      for (GeoResult<RedisGeoCommands.GeoLocation<String>> item : geoResults.getContent()) {
        Long shopId = Long.parseLong(item.getContent().getName());
        IsgDictShopInfo isgSameDictShop = this.isgDictStoreInfoMapper.selectById(shopId);
        if(!ObjectUtils.isEmpty(isgSameDictShop)){
          IsgActivityDictShopInfo isgActivityDictShopInfo = isgActivityDictStoreInfoMapper.selectIsgDictShopByBusCode(isgSameDictShop.getBusCode());
          // 距离相近且商家相同--认为是同一家门店
          if(isgActivityDictShopInfo.getKaName().equals(shopKa)){
            isgICDictStoreInfoMapper.updateSameShopFlag(icDirectShopInfo.getId(), isgActivityDictShopInfo.getBusCode(), item.getDistance().getValue());
            break;
          }
        }
      }
    } catch (Exception e) {
      logger.error("转化异常", e);
    }
  }
}